using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using EzDeploy.Resources;

namespace EzDeploy.Core
{
    public class EmbedAssemblyTask : IEmbedAssemblyTask
    {
        private readonly IEmbeddedAssemblyCommand _action;

        public EmbedAssemblyTask(IEmbeddedAssemblyCommand action)
        {
            _action = action;
        }

        public void Run(Project project, IEnumerable<DeployGridItem> items)
        {
            var args = new TaskExecutingEventArgs();
            this.OnExecuting(args);
            if (args.Cancel)
            {
                this.OnComplete(new Result(ResultType.Canceled, args.Message));
                return;
            }

            if (Directory.Exists(project.DeployedDirectory))
            {
                Result result = null;
                var task = Task.Factory.StartNew(() => result = _action.Run(items, project));
                var waiter = task.GetAwaiter();

                waiter.OnCompleted(() => this.OnComplete(result));
            }
            else
                this.OnComplete(new Result(ResultType.Error, MessageResource.DeploymentDirectoryNotFound));
        }

        protected virtual void OnExecuting(TaskExecutingEventArgs args)
        {
            var handler = Executing;
            if (handler != null) handler(this, args);
        }

        protected virtual void OnComplete(Result args)
        {
            var handler = Executed;
            if (handler != null) handler(this, args);
        }

        public event TaskExecutingEventHandler Executing;
        public event TaskExecutedEventHandler Executed;
    }
}
